//
//  HealthyViewController.m
//  KeepFit
//
//  Created by Fuzzie Liu on 15/10/28.
//  Copyright © 2015年 Fuzzie Liu. All rights reserved.
//

#import "HealthyViewController.h"
#import "TYWaveProgressView.h"//灌水
#import "SOMotionDetector.h"//记步
#import "SOStepDetector.h"//记步
#import <FMDB.h>//FMDB 的类
#import "CoordinateItem.h"//统计图形
#import "DrawView.h"//画统计图

@interface HealthyViewController () <UICollectionViewDataSource, UICollectionViewDelegate>//签协议
{
    int stepCount;//临时步数
}
@property (nonatomic, strong
           ) UIView *stepView;//步数的视图
@property (nonatomic, strong) UIView *statisticsView;//统计视图的 View
@property (nonatomic, weak) TYWaveProgressView *waveProgressView1;//灌水打分
@property (nonatomic, strong) FMDatabase *db;//数据库对象
@property (strong, nonatomic) NSMutableArray *dataSource;//统计图形的数据数据
@property (assign, nonatomic) ChartViewType chartViewType;//显示统计图的类型
@property (nonatomic, strong) UICollectionView *collection;//下面统计图
@property (nonatomic, strong) UISegmentedControl *statisticalSegmentControl;//下面统计图类型
@property (nonatomic, strong) UIImageView *moveTypeImageView;//运动状态图
@property (nonatomic, strong) UIImageView *shakImageView;//是否震动图

@end

@implementation HealthyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //上面的记步 View
    self.stepView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height / 3)];
    self.stepView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.stepView];

    //下面的统计 View
    self.statisticsView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height / 3 + 64, self.view.bounds.size.width, self.view.bounds.size.height / 3 * 2)];
    self.statisticsView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.statisticsView];

    [self addWaveProgressView1];//添加灌水打分视图
    
    [_waveProgressView1 startWave];//灌水开始

    //加运动状态图片
    self.moveTypeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, (self.stepView.bounds.size.height / 3 * 2), (self.stepView.bounds.size.height - 40) / 3, (self.stepView.bounds.size.height - 40) / 3)];
    self.moveTypeImageView.backgroundColor = [UIColor clearColor];
    self.moveTypeImageView.image = [UIImage imageNamed:@"iconfont-xiuxizhong"];
    [self.stepView addSubview:self.moveTypeImageView];
    self.shakImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width - ((self.stepView.bounds.size.height - 40) / 3) - 20, (self.stepView.bounds.size.height / 3 * 2), (self.stepView.bounds.size.height - 40) / 3, (self.stepView.bounds.size.height - 40) / 3)];
    self.shakImageView.backgroundColor = [UIColor whiteColor];
    [self.shakImageView setImage:[UIImage imageNamed:@"iconfont-iconshouji"]];
    [self.stepView addSubview:self.shakImageView];

    //计步器的方法
    __weak HealthyViewController *weakSelf = self;//弱引用
    
    //检测运动状态
    [SOMotionDetector sharedInstance].motionTypeChangedBlock = ^(SOMotionType motionType) {
        NSString *type = @"";
        switch (motionType) {
            case MotionTypeNotMoving:
                type = @"iconfont-xiuxizhong";
                break;
            case MotionTypeWalking:
                type = @"iconfont-599kuaizhuangzoulu";
                break;
            case MotionTypeRunning:
                type = @"iconfont-paobu";
                break;
            case MotionTypeAutomotive:
                type = @"iconfont-chengche";
                break;
        }
        //把运动状态赋值给 label
        weakSelf.moveTypeImageView.image = [UIImage imageNamed:type];
    };
    
    //检测出是否在震动
    [SOMotionDetector sharedInstance].accelerationChangedBlock = ^(CMAcceleration acceleration) {
        BOOL isShaking = [SOMotionDetector sharedInstance].isShaking;
        NSString *text = isShaking ? @"iconfont-iconzhendong":@"iconfont-iconshouji";
        weakSelf.shakImageView.image = [UIImage imageNamed:text];
    };
    
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
        [SOMotionDetector sharedInstance].useM7IfAvailable = YES; //Use M7 chip if available, otherwise use lib's algorithm
    }
    
    //显示步数
    [[SOMotionDetector sharedInstance] startDetection];
    [[SOStepDetector sharedInstance] startDetectionWithUpdateBlock:^(NSError *error) {
        if (error) {
            NSLog(@"%@", error.localizedDescription);
            return;
        }
        stepCount++;
        //水波显示步数
        _waveProgressView1.numberLabel.text = [NSString stringWithFormat:@"%d",stepCount];
        CGFloat percentage = stepCount / 100.0;
        _waveProgressView1.percent = percentage;
        [_waveProgressView1 startWave];
    }];

    //数据库
    [self createDataBase];
    
    //插入测试数据,第一次运行的时候解开封印,之后运行再封印
//    [self insertTestDate];
    
    //显示统计图形
    self.dataSource = [self seleteAllToday];
    if (self.dataSource.count == 0) {
        //没有数据
        NSLog(@"没有数据");
    }else{
        //显示数据的统计图样式
        self.chartViewType = BarChartViewType;
        //画图
        [self buildView];
    }

    //添加CollectionView
    UICollectionViewFlowLayout *collectionLayout = [[UICollectionViewFlowLayout alloc] init];
    collectionLayout.itemSize = CGSizeMake(self.statisticsView.bounds.size.width, self.statisticsView.bounds.size.height - 170);
    collectionLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    collectionLayout.minimumLineSpacing = 0;
    self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 30, self.statisticsView.bounds.size.width, self.statisticsView.bounds.size.height - 175) collectionViewLayout:collectionLayout];
    self.collection.backgroundColor = [UIColor whiteColor];
    self.collection.pagingEnabled = YES;
    self.collection.delegate = self;
    self.collection.dataSource = self;
    [self.statisticsView addSubview:self.collection];
    [self.collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"coll"];

    //加日周月年
    UISegmentedControl *segmentControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"日",@"周",@"月",@"年", nil]];
    segmentControl.frame = CGRectMake(0, 0, self.statisticsView.bounds.size.width, 30);
    segmentControl.backgroundColor = [UIColor whiteColor];
    segmentControl.selectedSegmentIndex = 0;
    [segmentControl addTarget:self action:@selector(segmentControlAction:) forControlEvents:UIControlEventValueChanged];
    [self.statisticsView addSubview:segmentControl];

    //加统计图类型
    self.statisticalSegmentControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"折线图",@"饼状图",@"柱状图", nil]];
    self.statisticalSegmentControl.frame = CGRectMake(0, self.statisticsView.bounds.size.height - 145, self.statisticsView.bounds.size.width, 30);
    self.statisticalSegmentControl.backgroundColor = [UIColor whiteColor];
    [self.statisticsView addSubview:self.statisticalSegmentControl];
    self.statisticalSegmentControl.selectedSegmentIndex = 0;
    [self.statisticalSegmentControl addTarget:self action:@selector(statisticalSegmentControlAction:) forControlEvents:UIControlEventValueChanged];
}

//添加灌水视图的执行方法
- (void)addWaveProgressView1
{
    //设置 frame
    TYWaveProgressView *waveProgressView = [[TYWaveProgressView alloc]initWithFrame:CGRectMake((self.stepView.bounds.size.width - self.stepView.bounds.size.height + 20) / 2, 10, self.stepView.bounds.size.height - 20, self.stepView.bounds.size.height - 20)];
    waveProgressView.waveViewMargin = UIEdgeInsetsMake(15, 15, 20, 20);
    waveProgressView.backgroundImageView.image = [UIImage imageNamed:@"bg_tk_003"];
    waveProgressView.numberLabel.text = @"0";
    waveProgressView.numberLabel.font = [UIFont boldSystemFontOfSize:70];
    waveProgressView.numberLabel.textColor = [UIColor whiteColor];
    waveProgressView.unitLabel.text = @"步";
    waveProgressView.unitLabel.font = [UIFont boldSystemFontOfSize:20];
    waveProgressView.unitLabel.textColor = [UIColor whiteColor];
    waveProgressView.explainLabel.text = @"步数";
    waveProgressView.explainLabel.font = [UIFont systemFontOfSize:20];
    waveProgressView.explainLabel.textColor = [UIColor whiteColor];
    //百分比
    waveProgressView.percent = 0;
    [self.stepView addSubview:waveProgressView];
    _waveProgressView1 = waveProgressView;
    [_waveProgressView1 startWave];
}

//创建数据库
- (void)createDataBase{
    //拼接一个数据库路径
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"KeepFit.sqlite"];
    NSLog(@"%@",path);
    //创建数据库实例对象
    self.db = [FMDatabase databaseWithPath:path];
    //打开数据库
    if (![self.db open]) {
        NSLog(@"数据库打开失败");
    }else{
        NSLog(@"打开数据库成功");
        //打开数据库成功的话就创建表
        BOOL result = [self.db executeUpdate:@"create table step (datetime text primary key, number integer);"];
        [self.db executeUpdate:@"create table daystep (datetime text primary key, number integer);"];
        [self.db executeUpdate:@"create table weekstep (datetime text primary key, number integer);"];
        [self.db executeUpdate:@"create table monthstep (datetime text primary key, number integer);"];
        [self.db executeUpdate:@"create table yearstep (datetime text primary key, number integer);"];
        [self.db executeUpdate:@"create table nowstep (datetime text primary key, number integer);"];
        if (result) {
            NSLog(@"创建表成功");
        }else{
            NSLog(@"创建表失败");
        }
    }
}

//得到当前时间的字符串
- (NSString *)nowDateString{
    NSDate *date = [NSDate date];
    NSString *dateStr = [NSString stringWithFormat:@"%@",date];
    dateStr = [dateStr substringToIndex:13];
    NSLog(@"时间:%@",dateStr);
    return dateStr;
}

//插入数据
- (void)insert{
    NSString *datetimeStr = [self nowDateString];
    NSNumber *number = [NSNumber numberWithInt:stepCount];
    int begoreDatetime = [self selete];
    if (begoreDatetime >0) {
        [self update];
    }else{
        BOOL result = [self.db executeUpdate:@"insert into step (datetime, number) values (?, ?);",datetimeStr,number];
        if (result) {
            NSLog(@"插入数据成功");
        }else{
            NSLog(@"插入数据失败");
        }
    }
}

//插入数据
- (int)selete{
    FMResultSet *rs = [self.db executeQuery:@"select number from step where datetime = ?;",[self nowDateString]];
    if(rs.next) {
        return [rs intForColumn:@"number"];
    }
    return 0;
}

//更新数据
- (void)update{
    NSNumber *number = [NSNumber numberWithInt:stepCount];
    BOOL result = [self.db executeUpdate:@"update step set number = ? where datetime = ?;",number, [self nowDateString]];
    if (result) {
        NSLog(@"修改数据成功");
    }else{
        NSLog(@"修改数据失败");
    }
}


//查找所有当日数据
- (NSMutableArray *)seleteAllToday{
    NSString *todayStr = [NSString stringWithFormat:@"%@%%",[[self nowDateString] substringToIndex:10]];
    FMResultSet *rs = [self.db executeQuery:@"select * from step where datetime like ?;",todayStr];
    NSMutableArray *tempMutableArray = [NSMutableArray array];
    while (rs.next) {
        NSString *datetimeStr = [rs stringForColumn:@"datetime"];
        NSString *numberStr = [NSString stringWithFormat:@"%d",[rs intForColumn:@"number"]];
        NSLog(@"数据库里面的数据:%@,%@",datetimeStr,numberStr);
        NSString *subDatetimeStr = [datetimeStr substringFromIndex:11];
        CoordinateItem *item = [[CoordinateItem alloc] initWithXValue:subDatetimeStr withYValue:numberStr withColor:[UIColor colorWithRed: (arc4random() % 256 / 255.0) green:(arc4random() % 256 / 255.0) blue:(arc4random() % 256 / 255.0) alpha:1.0]];
        [tempMutableArray addObject:item];
    }
    return tempMutableArray;
}

//查找所有当星期数据
- (NSMutableArray *)seleteAllWeek{
    NSString *todayStr = [NSString stringWithFormat:@"%@%%",[[self nowDateString] substringToIndex:7]];
    FMResultSet *rs = [self.db executeQuery:@"select * from daystep where datetime like ?;",todayStr];
    NSMutableArray *tempMutableArray = [NSMutableArray array];
    while (rs.next) {
        NSString *datetimeStr = [rs stringForColumn:@"datetime"];
        NSString *numberStr = [NSString stringWithFormat:@"%d",[rs intForColumn:@"number"]];
        NSLog(@"数据库里面的数据:%@,%@",datetimeStr,numberStr);
        NSString *subDatetimeStr = [datetimeStr substringFromIndex:9];
        CoordinateItem *item = [[CoordinateItem alloc] initWithXValue:subDatetimeStr withYValue:numberStr withColor:[UIColor colorWithRed: (arc4random() % 256 / 255.0) green:(arc4random() % 256 / 255.0) blue:(arc4random() % 256 / 255.0) alpha:1.0]];
        [tempMutableArray addObject:item];
    }
    return tempMutableArray;
}

//查找当月所有数据
- (NSMutableArray *)seleteAllMonth{
    NSString *todayStr = [NSString stringWithFormat:@"%@%%",[[self nowDateString] substringToIndex:7]];
    FMResultSet *rs = [self.db executeQuery:@"select * from daystep where datetime like ?;",todayStr];
    NSMutableArray *tempMutableArray = [NSMutableArray array];
    while (rs.next) {
        NSString *datetimeStr = [rs stringForColumn:@"datetime"];
        NSString *numberStr = [NSString stringWithFormat:@"%d",[rs intForColumn:@"number"]];
        NSLog(@"数据库里面的数据:%@,%@",datetimeStr,numberStr);
        NSString *subDatetimeStr = [datetimeStr substringFromIndex:8];
        CoordinateItem *item = [[CoordinateItem alloc] initWithXValue:subDatetimeStr withYValue:numberStr withColor:[UIColor colorWithRed: (arc4random() % 256 / 255.0) green:(arc4random() % 256 / 255.0) blue:(arc4random() % 256 / 255.0) alpha:1.0]];
        [tempMutableArray addObject:item];
    }
    return tempMutableArray;
}

//查找当年所有数据
- (NSMutableArray *)seleteAllYear{
    NSString *todayStr = [NSString stringWithFormat:@"%@%%",[[self nowDateString] substringToIndex:4]];
    FMResultSet *rs = [self.db executeQuery:@"select * from monthstep where datetime like ?;",todayStr];
    NSMutableArray *tempMutableArray = [NSMutableArray array];
    while (rs.next) {
        NSString *datetimeStr = [rs stringForColumn:@"datetime"];
        NSString *numberStr = [NSString stringWithFormat:@"%d",[rs intForColumn:@"number"]];
        NSLog(@"数据库里面的数据:%@,%@",datetimeStr,numberStr);
        NSString *subDatetimeStr = [datetimeStr substringFromIndex:5];
        CoordinateItem *item = [[CoordinateItem alloc] initWithXValue:subDatetimeStr withYValue:numberStr withColor:[UIColor colorWithRed: (arc4random() % 256 / 255.0) green:(arc4random() % 256 / 255.0) blue:(arc4random() % 256 / 255.0) alpha:1.0]];
        [tempMutableArray addObject:item];
    }
    return tempMutableArray;
}

//创建统计图视图
- (void)buildView
{
    switch (self.chartViewType)
    {
        case LineChartViewType:
        {
            //设置图形的 frame
            DrawView *drawLineChartView = [[DrawView alloc] initWithFrame:CGRectMake(0, 30, self.statisticsView.bounds.size.width, self.statisticsView.bounds.size.height - 170)withDataSource:self.dataSource withType:LineChartViewType withAnimation:YES];
            //只有当视图加载出来(即显示出来的时候才会调用drawRect方法)
            [self.statisticsView addSubview:drawLineChartView];
        }
            break;
        case BarChartViewType:
        {
            //绘制图形
            DrawView *drawBarChartView = [[DrawView alloc] initWithFrame:CGRectMake(0, 30, self.statisticsView.bounds.size.width, self.statisticsView.bounds.size.height - 170)withDataSource:self.dataSource withType:BarChartViewType withAnimation:YES];
            [self.statisticsView addSubview:drawBarChartView];
        }
            break;
        case PieChartViewType:
        {
            //绘制图形
            DrawView *drawPieChartView = [[DrawView alloc] initWithFrame:CGRectMake(0, 30, self.statisticsView.bounds.size.width, self.statisticsView.bounds.size.height - 170)withDataSource:self.dataSource withType:PieChartViewType withAnimation:YES];
            [self.statisticsView addSubview:drawPieChartView];
        }
            break;
        default:
            break;
    }
}

//插入测试数据
- (void)insertTestDate{
    //插入小时测试数据
    NSString *year = [NSString string];
    NSString *manth = [NSString string];
    NSString *day = [NSString string];
    NSString *time = [NSString string];
    for (NSInteger i = 2014; i <= 2015; i ++) {//年
        for (NSInteger j = 1; j <= 12; j ++) {//月
            NSInteger x = 28;
            if (j == 2) {
                if (i % 4 == 0 && i % 100 != 0) {
                    x = 29;
                }else{
                    x = 28;
                }
            }else if (j == 1 || j == 3 || j == 5 || j == 7 || j == 8 || j == 10 || j == 12){
                x = 31;
            }else{
                x = 30;
            }
            for (NSInteger k = 1; k <= x; k ++) {//日
                for (NSInteger l = 0; l <= 23; l ++) {//时
                    year = [NSString stringWithFormat:@"%ld",i];
                    if (j < 10) {
                        manth = [NSString stringWithFormat:@"0%ld",j];
                    }else{
                        manth = [NSString stringWithFormat:@"%ld",j];
                    }
                    if (k < 10) {
                        day = [NSString stringWithFormat:@"0%ld",k];
                    }else{
                        day = [NSString stringWithFormat:@"%ld",k];
                    }
                    if (l < 10) {
                        time = [NSString stringWithFormat:@"0%ld",l];
                    }else{
                        time = [NSString stringWithFormat:@"%ld",l];
                    }
                    
                    NSString *datatimeStr = [NSString stringWithFormat:@"%@-%@-%@ %@",year,manth,day,time];
                    NSInteger numberInteger = arc4random() % 101;
                    NSNumber *numberNumber = [NSNumber numberWithInteger:numberInteger];
                    [self.db executeUpdate:@"insert into step (datetime, number) values (?, ?);",datatimeStr,numberNumber];
                    NSLog(@"小时数据:%@, %@",datatimeStr,numberNumber);
                }
            }
        }
    }
    
    //插入日数据
    for (NSInteger i = 2014; i <= 2015; i ++) {//年
        for (NSInteger j = 1; j <= 12; j ++) {//月
            NSInteger x = 28;
            if (j == 2) {
                if (i % 4 == 0 && i % 100 != 0) {
                    x = 29;
                }else{
                    x = 28;
                }
            }else if (j == 1 || j == 3 || j == 5 || j == 7 || j == 8 || j == 10 || j == 12){
                x = 31;
            }else{
                x = 30;
            }
            for (NSInteger k = 1; k <= x; k ++) {//日
                year = [NSString stringWithFormat:@"%ld",i];
                if (j < 10) {
                    manth = [NSString stringWithFormat:@"0%ld",j];
                }else{
                    manth = [NSString stringWithFormat:@"%ld",j];
                }
                if (k < 10) {
                    day = [NSString stringWithFormat:@"0%ld",k];
                }else{
                    day = [NSString stringWithFormat:@"%ld",k];
                }
                NSString *datatimeStr = [NSString stringWithFormat:@"%@-%@-%@%%",year,manth,day];
                FMResultSet *rs = [self.db executeQuery:@"select sum(number) from step where datetime like ?;",datatimeStr];
                while (rs.next) {
                    NSInteger numberInteger = [rs intForColumn:@"sum(number)"];
                    NSNumber *numberNumber = [NSNumber numberWithInteger:numberInteger];
                    NSString *subDatetimeStr = [datatimeStr substringToIndex:10];
                    [self.db executeUpdate:@"insert into daystep (datetime, number) values (?, ?);",subDatetimeStr,numberNumber];
                    NSLog(@"日数据:%@,%@",subDatetimeStr,numberNumber);
                }
            }
        }
    }
    
    //插入月数据
    for (NSInteger i = 2014; i <= 2015; i ++) {//年
        for (NSInteger j = 1; j <= 12; j ++) {//月
            year = [NSString stringWithFormat:@"%ld",i];
            if (j < 10) {
                manth = [NSString stringWithFormat:@"0%ld",j];
            }else{
                manth = [NSString stringWithFormat:@"%ld",j];
            }
            NSString *datatimeStr = [NSString stringWithFormat:@"%@-%@%%",year,manth];
            FMResultSet *rs = [self.db executeQuery:@"select sum(number) from daystep where datetime like ?;",datatimeStr];
            while (rs.next) {
                NSInteger numberInteger = [rs intForColumn:@"sum(number)"];
                NSNumber *numberNumber = [NSNumber numberWithInteger:numberInteger];
                NSString *subDatetimeStr = [datatimeStr substringToIndex:7];
                [self.db executeUpdate:@"insert into monthstep (datetime, number) values (?, ?);",subDatetimeStr,numberNumber];
                NSLog(@"月数据:%@,%@",subDatetimeStr,numberNumber);
            }
        }
    }
    
    //插入年数据
    for (NSInteger i = 2014; i <= 2015; i ++) {//年
        year = [NSString stringWithFormat:@"%ld",i];
        NSString *datatimeStr = [NSString stringWithFormat:@"%@%%",year];
        FMResultSet *rs = [self.db executeQuery:@"select sum(number) from monthstep where datetime like ?;",datatimeStr];
        while (rs.next) {
            NSInteger numberInteger = [rs intForColumn:@"sum(number)"];
            NSNumber *numberNumber = [NSNumber numberWithInteger:numberInteger];
            NSString *subDatetimeStr = [datatimeStr substringToIndex:4];
            [self.db executeUpdate:@"insert into yearstep (datetime, number) values (?, ?);",subDatetimeStr,numberNumber];
            NSLog(@"年数据:%@,%@",subDatetimeStr,numberNumber);
        }
    }
    [self.db executeUpdate:@"insert into nowstep (datetime, number) values (?, ?);",@"sdfsdfsdfs",@0];
}

//collectionView 的代理方法,一共有多少个item
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 3;
}

//collection的代理方法,设置 cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *collectionCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"coll" forIndexPath:indexPath];
    if (self.dataSource.count == 0) {
    }else{
        switch (indexPath.item) {
            case 0:
            {
                DrawView *drawLineChartView = [[DrawView alloc] initWithFrame:CGRectMake(0, 0, self.statisticsView.bounds.size.width, self.statisticsView.bounds.size.height - 170)withDataSource:self.dataSource withType:LineChartViewType withAnimation:YES];
                [collectionCell addSubview:drawLineChartView];
                return collectionCell;
            }
                break;
            case 1:
            {
                DrawView *drawPieChartView = [[DrawView alloc] initWithFrame:CGRectMake(0, 0, self.statisticsView.bounds.size.width, self.statisticsView.bounds.size.height - 170)withDataSource:self.dataSource withType:PieChartViewType withAnimation:YES];
                [collectionCell addSubview:drawPieChartView];
                return collectionCell;
            }
                break;
            case 2:
            {
                DrawView *drawBarChartView = [[DrawView alloc] initWithFrame:CGRectMake(0, 0, self.statisticsView.bounds.size.width, self.statisticsView.bounds.size.height - 170)withDataSource:self.dataSource withType:BarChartViewType withAnimation:YES];
                [collectionCell addSubview:drawBarChartView];
                return collectionCell;
            }
                break;
            default:
                break;
        }
    }
    return collectionCell;
}

//点击下面的视图类型的SegmentControl, collectionView 的偏移量变化
- (void)statisticalSegmentControlAction:(UISegmentedControl *)btn{
    switch([btn selectedSegmentIndex])
    {
        case 0:{
            CGPoint point = CGPointMake(0.0, 0.0);
            [self.collection setContentOffset:point animated:YES];
        }
            break;
        case 1:{
            CGPoint point = CGPointMake(self.view.bounds.size.width, 0.0);
            [self.collection setContentOffset:point animated:YES];
        }
            break;
        case 2:{
            CGPoint point = CGPointMake(self.view.bounds.size.width * 2, 0.0);
            [self.collection setContentOffset:point animated:YES];
        }
            break;
        default:
            break;
    }
}

// 上面的segmentControl的点击方法
- (void)segmentControlAction:(UISegmentedControl *)btn{
    switch ([btn selectedSegmentIndex]) {
        case 0:{//按日显示
            [self.dataSource removeAllObjects];
            self.dataSource = [self seleteAllToday];
            [self.collection reloadData];
        }
            break;
        case 1:{//按周显示
            [self.dataSource removeAllObjects];
            self.dataSource = [self seleteAllWeek];
            [self.collection reloadData];
        }
            break;
        case 2:{//按月显示
            [self.dataSource removeAllObjects];
            self.dataSource = [self seleteAllMonth];
            [self.collection reloadData];
        }
            break;
        case 3:{//按年显示
            [self.dataSource removeAllObjects];
            self.dataSource = [self seleteAllYear];
            [self.collection reloadData];
        }
            break;
            
        default:
            break;
    }
}

//scrollView滑动的偏移量来改变下面的统计视图的选择index
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.x < self.view.bounds.size.width / 2) {
        self.statisticalSegmentControl.selectedSegmentIndex = 0;
    }else if (scrollView.contentOffset.x < self.view.bounds.size.width / 2 * 3){
        self.statisticalSegmentControl.selectedSegmentIndex = 1;
    }else{
        self.statisticalSegmentControl.selectedSegmentIndex = 2;
    }
}

//视图将要出现,读取之前走过的步数
- (void)viewWillAppear:(BOOL)animated{
    NSLog(@"视图将要出现");
    stepCount = [self seleteNowStep];
    _waveProgressView1.numberLabel.text = [NSString stringWithFormat:@"%d",stepCount];
    CGFloat percentage = stepCount / 100.0;
    _waveProgressView1.percent = percentage;
    [_waveProgressView1 startWave];
    NSLog(@"上次的步数是:%d",[self seleteNowStep]);
}

//视图将要消失,存储现在已经走得步数
- (void)viewWillDisappear:(BOOL)animated{
    NSLog(@"视图将要消失");
    NSLog(@"已经走得步数是:%d",stepCount);
    NSNumber *number = [NSNumber numberWithInt:stepCount];
    [self updateWithDatetime:@"sdfsdfsdfs" Numner:number];
}

//更新现在的数据
- (void)updateWithDatetime:(NSString *)datetime Numner:(NSNumber *)number{
    BOOL result = [self.db executeUpdate:@"update nowstep set number = ? where datetime = ?;",number, datetime];
    if (result) {
        NSLog(@"修改数据成功");
    }else{
        NSLog(@"修改数据失败");
    }
}

//查找现在的步数
- (int)seleteNowStep{
    FMResultSet *rs = [self.db executeQuery:@"select * from nowstep where datetime = ?;",@"sdfsdfsdfs"];
    if(rs.next) {
        int number = [rs intForColumn:@"number"];
        NSLog(@"方法里面得到的步数:%d",number);
        return number;
    }
    return 0;
}


//内存警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
